package cn.edu.xaut.servlet;

import cn.edu.xaut.Dao.UsersDao;
import cn.edu.xaut.bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "Login", urlPatterns = "/loginServlet")
public class LoginServlet extends HttpServlet {


    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8"); // 设置请求编码
        resp.setContentType("text/html;charset=UTF-8"); // 设置响应编码
        resp.setCharacterEncoding("UTF-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 从数据库中获取用户信息
        UsersDao usersDao = new UsersDao();
        try{
            User user = usersDao.findOne(username, password);
            if(user !=null){
                resp.getWriter().write("登录成功");
                req.getSession().setAttribute("user", user);
                resp.sendRedirect("goodsmarket");
            }
            else{
                resp.getWriter().write("登录失败");
                resp.getWriter().println("<a href='login.jsp'>返回登录</a>");
            }
        }catch (SQLException e){
            throw new RuntimeException(e);
        }catch (ClassNotFoundException e){
            throw new RuntimeException(e);
        }

    }


    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        this.doPost(req, resp);
    }
}
